<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="新增SKU"
    width="1000"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <el-table border ref="xTable" :data="form">
      <el-table-column prop="sku" label="SKU中文名" width="200">
        <template #header>
          <div>SKU中文名<span class="text-red-500 text-lg">*</span></div>
        </template>
        <template #default="{ row }">
          <el-input
            v-model="row.sku_cn_title"
            type="textarea"
            placeholder="请输入"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="sku" label="SKU英文名" width="200">
        <template #header>
          <div class="flex items-center">
            <div class="mr-2">SKU英文名<span class="text-red-500 text-lg">*</span></div>
            <el-button type="primary" link @click="translateName">翻译</el-button>
          </div>
        </template>
        <template #default="{ row }">
          <el-input
            v-model="row.sku_en_title"
            type="textarea"
            placeholder="请输入"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="sku" label="属性" min-width="400">
        <template #header>
          <div class="flex items-center">
            <div class="mr-2">属性<span class="text-red-500 text-lg">*</span></div>
            <el-button type="primary" link @click="translateAttribute">翻译</el-button>
          </div>
        </template>
        <template #default="{ row }">
          <div
            class="flex items-center mb-2"
            v-for="(item, index) in row.attribute"
            :key="index"
          >
            {{ item.group_name }}：<el-input
              class="w-40 mr-2"
              v-model="item.attribute_cn"
              placeholder="请输入中文"
            ></el-input
            ><el-input
              class="w-40"
              v-model="item.attribute_en"
              placeholder="请输入英文"
            ></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sku" label="操作" width="120">
        <template #default="{ row, $index }">
          <el-button type="primary" link @click="handleAdd">新增</el-button>
          <el-button type="danger" link @click="handleDelete($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save()">保 存</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="jsx">
import { reactive, toRefs } from "vue";
import { translationBatch } from "@/api/index";
import { ElMessage, ElMessageBox } from "element-plus";
import { deepClone } from "@/utils/index";
import { getSKUInfo } from "../../api.js";

const emit = defineEmits(["push"]);

let formData = reactive(inject("form"));

const data = reactive({
  form: [],
  visible: false,
  attributes: [],
  loading: false,
  load: false,
});
const { form, visible, attributes, loading, load } = toRefs(data);

const open = async () => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  initForm();
  visible.value = true;
};

const initForm = () => {
  const attribute = formData.value.goods_sku[0].sku_specification.header.map((i) => {
    return {
      group_name: i.name || i.value,
      group_en_name: i.key,
      attribute_cn: "",
      attribute_en: "",
    };
  });
  attributes.value = deepClone(attribute);
  form.value = [
    {
      sku_cn_title: "",
      sku_en_title: "",
      attribute,
      spu: formData.value.spu,
    },
  ];
};

// 翻译英语
const translateName = () => {
  let arr = [];

  form.value &&
    form.value.forEach((item) => {
      arr.push(item.sku_cn_title);
    });

  let languageArr = ["en"];
  let texts = {};
  languageArr.forEach((i) => {
    texts[i] = arr;
  });

  let param = {
    texts,
    use_proxy: true,
  };
  translationBatch(param).then((res) => {
    form.value.forEach((item, index) => {
      if (res.data["en"] && res.data["en"].length) {
        item.sku_en_title = res.data["en"][index].trim();
      }
    });
    ElMessage.success(res.msg);
  });
};

const translateAttribute = () => {
  const newArray = form.value[0].attribute.map((_, index) =>
    form.value.map((item) => item.attribute[index].attribute_cn)
  );
  translateArrayAndSendToApi(newArray);
};

const translateArrayAndSendToApi = async (array) => {
  const translatedArray = await Promise.all(
    array.map((item) => translateToEnglish(item))
  );
  for (let i = 0; i < form.value.length; i++) {
    for (let j = 0; j < form.value[i].attribute.length; j++) {
      form.value[i].attribute[j].attribute_en = translatedArray[j].en[i] || ""; // 适应数组长度不一致的情况
    }
  }
  ElMessage.success("翻译成功");
};

const translateToEnglish = async (array) => {
  try {
    const param = {
      texts: {
        en: array,
      },
      use_proxy: true,
    };
    const result = await translationBatch(param);
    return result.data;
  } catch (error) {
    return "";
  }
};

const handleAdd = () => {
  form.value.push({
    sku_cn_title: "",
    sku_en_title: "",
    attribute: deepClone(attributes.value),
    spu: formData.value.spu,
  });
};

const handleDelete = (index) => {
  if (form.value.length <= 1) {
    ElMessage.error("至少保留一条");
    return;
  }
  form.value.splice(index, 1);
};

const save = async () => {
  loading.value = true;
  try {
    const res = await getSKUInfo({ params: form.value });
    const primaryAttribute = formData.value.goods_sku.find((i) => i.main_attribute == 1);
    const create_list = res.data.map((item, index) => {
      item.sku_cn_title = form.value[index].sku_cn_title;
      item.sku_en_title = form.value[index].sku_en_title;
      // item.custom_sku = item.sku;
      // item.sku = "";
      let specifications = "";
      const skuSpec = item.sku_specification;

      if (skuSpec && skuSpec.header && skuSpec.attributes) {
        const values = Object.values(skuSpec.attributes);
        specifications = values.join(",");
      }
      item.goods_sku_title = [
        {
          custom_sku: item.custom_sku,
          language_code: "zh",
          language_id: 1,
          show: true,
          sku: item.sku,
          specifications,
          title: form.value[index].sku_cn_title,
        },
        {
          custom_sku: item.custom_sku,
          language_code: "en",
          language_id: 2,
          show: true,
          sku: item.sku,
          specifications,
          title: form.value[index].sku_en_title,
        },
      ];
      item.sku_product_type = primaryAttribute?.sku_product_type;

      return item;
    });

    const difference = findFirstDifference(formData.value.goods_sku, create_list);

    if (difference && difference.length) {
      loading.value = false;

      return ElMessageBox({
        title: "属性重复",
        message: <div>{difference.map((d) => h("p", null, d))}</div>,
      });
    }
    emit("push", create_list);
    close();
    loading.value = false;
  } catch (e) {
    loading.value = false;
    throw Error(e);
  }
};

const findFirstDifference = (arr1, arr2) => {
  const differences = [];
  for (const obj1 of arr1) {
    for (const obj2 of arr2) {
      const obj3 = obj1.sku_specification?.attributes;
      const obj4 = obj2.sku_specification?.attributes;
      const difference = areObjectsDifferent(obj3, obj4);

      if (difference) {
        differences.push(difference);
      }
    }
  }
  return differences;
};

const areObjectsDifferent = (obj1, obj2) => {
  const values1 = Object.values(obj1).sort();
  const values2 = Object.values(obj2).sort();

  const differences = [];
  const duplicateValues = values1.filter((value) => values2.includes(value));
  if (JSON.stringify(values1) == JSON.stringify(values2)) {
    differences.push(`重复属性: ${duplicateValues.join(", ")}`);
  }

  return differences.length > 0 ? differences : "";
};

const close = () => {
  visible.value = false;
};

defineExpose({ open });
</script>
<style lang="scss" scoped></style>
